package com.miaosha;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.common.exception.CommonException;
import com.common.exception.consts.MiaoShaErrorCode;
import com.miaosha.fx.jsjava.Java2Js;
import com.utils.DateUtil;
import com.utils.JSUtils;

@SuppressWarnings({ "deprecation","unchecked"})
public class MediaService {
	
	public static final String COOKIE = "Hm_lvt_99ff99f801ce503d1de8d4b8ffbed421=1447914996; Hm_lvt_4b9a2b6647c9bdd3d01c28ea3f46049b=1448123832,1448200382,1448372177,1449537053; midea_mk=c233338facd745c3b4a9c1607592b4a8; OAM_LANG_PREF=v1.0~cHJlZmVycmVkTGFuZ3VhZ2U9emh+ZGVmYXVsdExhbmd1YWdlTWFya2VyPWZhbHNl; oam_locale=zh; mip_lang=zh; midea_sso_token=NwihewE3kaa%2F0ebethvmc4Ar4JURF1uPOA7C8f84UjKRuNnBqPvLGA%3D%3D; OAMAuthnHintCookie=1; SRMMAT=Q0m9yfLRCMkn6Kyn3pziBXBKdd; uid=6293352; sukey=gWACfcPGJk; mtag=%3B40005.1.9%3B30001.1.2%3B10003.2.10200%3B20056.8.201; env=%7B%22channel%22%3A3%2C%22regsrc%22%3A%2220.20006.20006010%22%7D; Hm_lvt_94d2fcdc25bf11213329895f51da83d0=1451200130,1451263994,1451350536,1451440853; Hm_lpvt_94d2fcdc25bf11213329895f51da83d0=1451441025";
	public static final String MIAOSHA_URL = "http://w.midea.com/coupon/get_user_coupon?obtainId=";//秒杀路径
	public static final String LOGIN_URL = "http://mall.midea.com/login/login_with_passwd";//登陆路径
	public static final String GET_NONCE_ID_URL = "http://w.midea.com/mlogin/get_nonce_id";//随机码路径
	public static final String COUPON_URL = "http://mall.midea.com/my/internal?mtag=30001.1.2";//内购首页路径
	public static final String SIGN_URL = "http://mall.midea.com/my/index/create_daily_score";//签到路径
	public static Logger logger = Logger.getLogger(MediaService.class);
	public static HttpClient httpClient = new DefaultHttpClient();
	private static List<Timer> timerList = new ArrayList<Timer>();
//	private static long delayTime = 0;//实际延迟时间
//	private static long normalDelayTime = 0;//正常延迟时间
	
	/**
	 * 获取登录随机码
	 * @return
	 * @throws Exception
	 */
	public static String getNonceid() throws Exception{
		String nonceid = null;
		try {
			HttpGet httpGet  = new HttpGet(GET_NONCE_ID_URL);
			HttpResponse response = httpClient.execute(httpGet);
			HttpEntity httpEntity = response.getEntity();
			String res = EntityUtils.toString(httpEntity, "UTF-8");
			JSONObject jsonObject = JSON.parseObject(res);
			nonceid = jsonObject.getJSONObject("data").get("strNonceId").toString();
			logger.info("登录随机码 = " + nonceid);
		} catch (Exception e) {
			throw new CommonException("获取登录随机码失败。", e);
		}
		
		return nonceid;
	}
	
	/**
	 * 获取当日优惠券id
	 * @return
	 * @throws Exception
	 */
	public static String getCouponId() throws Exception{
		String couponId = null;
		try {
			HttpGet httpGet  = new HttpGet(COUPON_URL);
			HttpResponse response = httpClient.execute(httpGet);
			HttpEntity httpEntity = response.getEntity();
			String res = EntityUtils.toString(httpEntity, "UTF-8");
			Document document = Jsoup.parse(res);
			couponId = document.getElementsByClass("coupon_btn").get(0).attr("data-oid");
			//如果是20号。。。。则另解析
			logger.info("优惠券id = " + couponId);
		} catch (Exception e) {
			throw new CommonException("获取优惠券信息失败。", e);
		}
		return couponId;
	}
	
	/**
	 * 获取当日优惠券id
	 * @return
	 * @throws Exception
	 */
	public static String[] getCouponIds(){
		String[] couponIds = null;
		try {
			HttpGet httpGet  = new HttpGet(COUPON_URL);
			HttpResponse response = httpClient.execute(httpGet);
			HttpEntity httpEntity = response.getEntity();
			String res = EntityUtils.toString(httpEntity, "UTF-8");
			Document document = Jsoup.parse(res);
			Elements couponBtns = document.getElementsByClass("coupon_btn");
			couponIds = new String[couponBtns.size()];
			for (int i = 0; i < couponIds.length; i++) {
				couponIds[i] = couponBtns.get(i).attr("data-oid");
			}
			logger.info("优惠券id = " + JSON.toJSONString(couponIds));
		} catch (Exception e) {
			throw new CommonException("获取优惠券信息失败。", e);
		}
		return couponIds;
	}
	
	/**
	 * 登录
	 * @param mobile
	 * @param passwd
	 * @throws Exception
	 */
	public static void login(String mobile, String passwd) throws Exception{
		String nonceid = getNonceid();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("mobile", mobile));
		params.add(new BasicNameValuePair("passwd", JSUtils.getMediaRegisterPwd(mobile, passwd, nonceid)));
		params.add(new BasicNameValuePair("nonceid", nonceid));
		HttpPost httpPost = new HttpPost(LOGIN_URL);
//		String[] proxyIp = "10.73.188.58:8888".split(":");
//		HttpHost proxy = new HttpHost(proxyIp[0], Integer.parseInt(proxyIp[1]), "http");
//		final RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
//		httpPost.setConfig(config);
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
		httpPost.setEntity(entity);
		HttpResponse response = httpClient.execute(httpPost);
		HttpEntity httpEntity = response.getEntity();
		String res = EntityUtils.toString(httpEntity);
		logger.info("登录结果 = " + res);
		if(StringUtils.isNotBlank(res)){
			throw new CommonException(MiaoShaErrorCode.LOGIN_FAIL,"登陆失败，账号或者密码错误");
		}
	}
	
	/**
	 * 秒杀定时任务
	 * @param startTime
	 * @param httpGet
	 */
	public static void createSchedule(final Date startTime,  final HttpGet httpGet){
		
//		{
//			Date delayStartTime = DateUtils.addSeconds(startTime, -15);
//			logger.info("创建测试网络延迟任务：" + DateUtil.format(delayStartTime, "yyyy-MM-dd HH:mm:ss.S") + "开始");
//			Timer timer = new Timer();
//			TimerTask task = new TimerTask() {  
//				   public void run() {  
//					   logger.info("默认设置延迟时间为：" + normalDelayTime);
//					   logger.info("开始测试网络延迟......");
//					   for (int i = 0; i < 3; i++) {
//						   MediaService.testDelay(httpGet);
//						   try {
//							   Thread.sleep(4000);
//						   } catch (Exception e) {
//								logger.equals(e);
//						   }
//					   }
//				   }     
//			};
//			timer.schedule(task, delayStartTime);
//		}
		
		logger.info("创建秒杀任务：" + DateUtil.format(startTime, "yyyy-MM-dd HH:mm:ss.S") + "开始");
		Timer timer = new Timer();
		TimerTask task = new TimerTask() {  
			   public void run() {  
//				   logger.info("默认设置延迟时间为：" + normalDelayTime);
//				   logger.info("开始测试网络延迟......");
//				   for (int i = 0; i < 200; i++) {
//					   MediaService.testDelay(httpGet);
//					   try {
//						   Thread.sleep(5000);
//					   } catch (Exception e) {
//							logger.equals(e);
//					   }
//				   }
//				   long sleepTime = normalDelayTime - delayTime;
//				   logger.info("校正网络延迟：" + sleepTime);
//				   if(sleepTime > 0){
//					   try {
//						   Thread.sleep(sleepTime);
//					   } catch (Exception e) {
//							logger.equals(e);
//					   }
//				   }
				   MediaService.miaosha(httpGet);
			   }     
		};
		timer.schedule(task, startTime);
//		timerList.add(timer);
	}
	
	/**
	 * 秒杀
	 * @param httpGet
	 */
	public static void miaosha(HttpGet httpGet){
		try {
			
			long beginTime = System.currentTimeMillis();
			HttpResponse httpResponse = httpClient.execute(httpGet);
			long endTime = System.currentTimeMillis();
			String s1 = "发送请求时间：" + DateUtil.format(new Date(beginTime), "yyyy-MM-dd HH:mm:ss.S");
			String s2 = "返回结果时间：" + DateUtil.format(new Date(endTime), "yyyy-MM-dd HH:mm:ss.S");
			String res = EntityUtils.toString(httpResponse.getEntity(), "utf8");
			Map<String,Object> map = JSON.parseObject(res, HashMap.class);
			String errcode = map.get("errcode").toString();
			String errmsg = map.get("errmsg").toString();
			if(StringUtils.isBlank(errmsg)){
				errmsg = "你貌似抢到了一张一折券......";
			}
			Java2Js.pushMessage(s1);
			Java2Js.pushMessage(s2);
			Java2Js.pushMessage(errmsg);
			logger.info(s1);
			logger.info(s2);
			logger.info(errcode+"："+errmsg);
		} catch (Exception e) {
			logger.error(e);
		}
	}
	
	/**
	 * 每日签到
	 * @throws Exception
	 */
	public static void sign() throws Exception{
		HttpGet httpGet  = new HttpGet(SIGN_URL);
		HttpResponse response = httpClient.execute(httpGet);
		String res = EntityUtils.toString(response.getEntity(), "UTF-8");
		logger.info("签到结果 = " + res);
	}
	
	/**
	 * 停止所有任务
	 */
	public static void stop(){
		for (int i = 0; i < timerList.size(); i++) {
			Timer timer = timerList.get(i);
			if(timer != null){
				try {
					timer.cancel();
				} catch (Exception e) {
				}
			}
		}
		timerList.clear();
	}
	
	/**
	 * 测试网络延迟
	 */
//	public static void testDelay(HttpGet httpGet){
//		try {
//			long beginTime = System.currentTimeMillis();
//			HttpResponse response = httpClient.execute(httpGet);
//			long endTime = System.currentTimeMillis();
//			EntityUtils.toString(response.getEntity(), "utf8");
//			delayTime = endTime - beginTime;
//			logger.info("实际延迟时间为：" + delayTime);
//		} catch (Exception e) {
//			logger.error(e);
//		}
//	}
}
